package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.pactera.madp.cp.api.dto.track.BehaviorTrackDto;
import com.pactera.madp.cp.api.entity.BehaviorTrackEntity;
import com.pactera.madp.cp.common.constant.BehaviorTrackFormatConst;
import com.pactera.madp.cp.service.IWorkContactService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class BehaviorTrackCustomFormServiceImpl extends BaseBehaviorTrackServer {

    @Override
    public void handleEvent(BehaviorTrackDto dto, IWorkEmployeeService workEmployeeService, IWorkContactService workContactService, HttpServletResponse response) throws Exception {
        //参数校验
        vildateParams(dto);

        //事件处理
        BehaviorTrackEntity entity = new BehaviorTrackEntity();
        BeanUtil.copyProperties(dto, entity);
        baseHandleEvent(entity, workEmployeeService, workContactService, this, response);

        //链接重定向
        response.sendRedirect(dto.getUrl());
    }

    @Override
    protected String buildData(BehaviorTrackEntity entity) {
        List<String> datas = new ArrayList<>();
        datas.add(entity.getExternalUsername());
        datas.add(entity.getTitle());
        datas.add(entity.getUrl());
        datas.add("");
        String content = String.format(BehaviorTrackFormatConst.CustomFormFormat, datas.toArray(new String[datas.size()]));

        return content;
    }


    /**
     * 参数校验
     * @param dto
     */
    private void vildateParams(BehaviorTrackDto dto) {
        if (StrUtil.isEmpty(dto.getTitle())) {
            throw new IllegalArgumentException("表单名称不能为空");
        }
    }
}

